package com.xbongbong.paas.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.utils.HttpHelper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.crm.help.SearchCustomerHelp;
import com.xbongbong.crm.util.FineClueUtil;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.BusinessFieldPojo;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.FineClueCompanyModel;
import com.xbongbong.paas.model.FineClueConsumptionModel;
import com.xbongbong.paas.model.FineClueUserModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.UserListDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.UserListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.FineClueService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.appmodule.pojo.dto.AppModuleSaveDTO;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.FineClueUrlConstant;
import com.xbongbong.pro.domain.entity.FineClueCompanyEntity;
import com.xbongbong.pro.domain.entity.FineClueConsumptionEntity;
import com.xbongbong.pro.domain.entity.FineClueUserEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.enums.BusinessFineClueEnum;
import com.xbongbong.pro.enums.FineClueEnum;
import com.xbongbong.pro.enums.FineClueToCustomerEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.FineClueErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueComboEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueFormEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueStatusEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.fineclue.pojo.TransferClueParamPOJO;
import com.xbongbong.pro.fineclue.pojo.dto.EnterpriseDetailGetDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueClueReleaseDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueConsumptionDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueCustomerDataDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueGetEnableBuinessDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueGetUseDosageDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueOfficiallyOpenDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueOpenTrialDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineCluePageGetDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueRedisTypeDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueUpdateDosageDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueUpdateListDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueUserDTO;
import com.xbongbong.pro.fineclue.pojo.dto.FineClueUserSurplusUsageDTO;
import com.xbongbong.pro.fineclue.pojo.dto.TransferClueStatusDTO;
import com.xbongbong.pro.fineclue.pojo.vo.EnterpriseDetailGetVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueConsumptionVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueGetEnableBuinessVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueMsgVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineCluePageGetVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueUserListVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueUserSurplusUsageVO;
import com.xbongbong.pro.fineclue.pojo.vo.FineClueUserVO;
import com.xbongbong.pro.fineclue.pojo.vo.TransferClueStatusVO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ExternalDataSourceEnum;
import com.xbongbong.saas.enums.business.FineClueContactInfoEnum;
import com.xbongbong.saas.enums.business.FineCluePageRouteEnum;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.service.AppModuleService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * @Author mingliang
 * @Description 精线索工商查询与搜客
 **/
@Service("fineClueServiceImpl")
public class FineClueServiceImpl implements FineClueService {

    private static final Logger LOG = LoggerFactory.getLogger(FineClueServiceImpl.class);

    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private UserService userService;
    @Resource
    private FineClueUserModel fineClueUserModel;
    @Resource
    private FineClueCompanyModel fineClueCompanyModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private UserModel userModel;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private SearchCustomerHelp searchCustomerHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private AppModuleService appModuleService;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private FineClueConsumptionModel fineClueConsumptionModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;




    @Override
    public EnterpriseDetailGetVO enterpriseGetInfo(EnterpriseDetailGetDTO enterpriseDetailGetDTO) throws XbbException {
        EnterpriseDetailGetVO enterpriseDetailGetVO = new EnterpriseDetailGetVO();
        String corpid = enterpriseDetailGetDTO.getCorpid();
        String userId = enterpriseDetailGetDTO.getUserId();
        String pid = enterpriseDetailGetDTO.getPid();
        Integer businessType = enterpriseDetailGetDTO.getBusinessType();
        // 新客户查看是否能使用精线索的工商查询
        FineClueCompanyEntity clueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.BUSINESS.getType());
        if (Objects.isNull(clueCompanyEntity)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280009);
        }
        if (clueCompanyEntity.getExtraExpiry() < DateUtil.getInt()) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280008);
        }
        if (!fineClueHelp.hasBusinessSearch(businessType)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280015);
        }
        JSONObject data = new JSONObject();
        try {
            String keyword = enterpriseDetailGetDTO.getKeyword();
            FineClueUserEntity clueUserEntity = fineClueUserModel.getByKey(corpid, userId);
            //已开通工商查询的公司，没有坐席的员工
            if (Objects.isNull(clueUserEntity)) {
                clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
            }
            if (Objects.isNull(clueUserEntity)) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280008);
            }
            String sign = fineClueHelp.getSign(clueUserEntity.getRegisterCorpid(), clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword(),enterpriseDetailGetDTO.getPlatform());
            if (Objects.isNull(sign)) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
            }
            //工商查询数据回显
            JSONObject baseInfo = fineClueHelp.dataBackfill(pid, sign);
            if (Objects.isNull(baseInfo)){
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
            }
            //精线索date内容
            JSONObject informationData = baseInfo.getJSONObject(StringConstant.JSON_DATA);
            if (Objects.isNull(informationData)){
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
            }
            LOG.info("精线索工商查询数据：{}", informationData);
            String registeredAddress = informationData.getString(BusinessFineClueEnum.REGISTERED_ADDRESS.getAttr());
            String provinceCity = informationData.getString(BusinessFineClueEnum.PROVINCE_CITY.getAttr());
            registeredAddress = provinceCity + registeredAddress;
            informationData.put(BusinessFineClueEnum.REGISTERED_ADDRESS.getAttr(),registeredAddress);
            //如果是客户工商查询
            data.put("pid", enterpriseDetailGetDTO.getPid());

            //经营时间需要特殊处理
            String operatingPeriod = informationData.getString("operatingPeriod");
            JSONObject operatingPeriodDate = getOperatingPeriod(operatingPeriod);
            informationData.put(BusinessFineClueEnum.OPERATING_PERIOD_START.getAttr(), operatingPeriodDate.getLong("operatingPeriodStart"));
            informationData.put(BusinessFineClueEnum.OPERATING_PERIOD_END.getAttr(), operatingPeriodDate.getLong("operatingPeriodEnd"));
            //成立日期，核准日期，注销日期修改为long型时间戳
            informationData.put(BusinessFineClueEnum.DATE_OF_ESTABLISHMENT.getAttr(), stringToLongTime(informationData.getString(BusinessFineClueEnum.DATE_OF_ESTABLISHMENT.getAttr())));
            informationData.put(BusinessFineClueEnum.CANCELLATION_DATE.getAttr(), stringToLongTime(informationData.getString(BusinessFineClueEnum.CANCELLATION_DATE.getAttr())));
            informationData.put(BusinessFineClueEnum.APPROVAL_DATE.getAttr(), stringToLongTime(informationData.getString(BusinessFineClueEnum.APPROVAL_DATE.getAttr())));
            //历史名称处理为String
            JSONArray historyName = informationData.getJSONArray(BusinessFineClueEnum.HISTORY_NAME.getAttr());
            StringBuilder historyNameString = new StringBuilder();
            if (CollectionsUtil.isNotEmpty(historyName)) {
                for (Object o : historyName) {
                    historyNameString.append(o).append(",");
                }
                String substring = historyNameString.substring(0, historyNameString.length() - 1);
                informationData.put(BusinessFineClueEnum.HISTORY_NAME.getAttr(), substring);
            } else {
                informationData.put(BusinessFineClueEnum.HISTORY_NAME.getAttr(), "");
            }

            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(enterpriseDetailGetDTO.getFormId(), enterpriseDetailGetDTO.getCorpid());
            List<FieldAttrEntity> fieldList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity fieldAttrEntity : fieldList) {
                FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldAttrEntity.getFieldType());
                DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
                BusinessFieldPojo businessFieldPojo = defaultAttr.getBusinessMatchAttr();
                if (Objects.nonNull(businessFieldPojo)) {
                    String attr = businessFieldPojo.getAttr();
                    BusinessFineClueEnum businessFineClueEnum = BusinessFineClueEnum.getByCode(businessFieldPojo.getCode());
                    if (businessFineClueEnum == null || StringUtils.isEmpty(attr) || fieldTypeEnum == null) {
                        continue;
                    }
                    if (!Objects.equals(businessFieldPojo.getSource(), "FineClueInfo")) {
                        continue;
                }
                    switch (fieldTypeEnum) {
                        case TEXT:
                            data.put(fieldAttrEntity.getAttr(), informationData.getString(attr));
                            break;
                        case NUM:
                            data.put(fieldAttrEntity.getAttr(), informationData.getInteger(attr));
                            break;
                        case COMBO:
                            // 下拉框转换成规范格式
                            JSONObject combo = new JSONObject();
                            if (Objects.equals(businessFineClueEnum.getFieldType(), FieldTypeEnum.TEXT.getType())) {
                                String comboStr = informationData.getString(attr);
                                combo.put(StringConstant.TEXT, comboStr);
                                combo.put(StringConstant.VALUE, comboStr);
                            } else if (Objects.equals(businessFineClueEnum.getFieldType(), FieldTypeEnum.NUM.getType())) {
                                combo.put(StringConstant.TEXT, informationData.getInteger(attr));
                                combo.put(StringConstant.VALUE, informationData.getInteger(attr));
                            }
                            data.put(fieldAttrEntity.getAttr(), combo);
                            break;
                        case DATETIME:
                            data.put(fieldAttrEntity.getAttr(), informationData.getLong(attr));
                            break;
                        case ADDRESS:
                            // 地址转换成规范格式
                            JSONObject addr = searchCustomerHelp.changeAddress(informationData.getString(attr));
                            data.put(fieldAttrEntity.getAttr(), addr);
                            LOG.info("--------------addr",addr);
                            break;
                        case SUB_FORM:
                            JSONArray jsonArray = informationData.getJSONArray(attr);
                            List<JSONObject> subArray = new ArrayList<>();
                            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                            List<? extends FieldAttrEntity> items = subForm.getItems();
                            for (Object obj : jsonArray) {
                                JSONObject subData = (JSONObject) obj;
                                JSONObject subObj = new JSONObject();
                                for (FieldAttrEntity item : items) {
                                    DefaultAttrPoJo subDefault = item.getDefaultAttr();
                                    BusinessFieldPojo subBusinessAttr = subDefault.getBusinessMatchAttr();
                                    if (Objects.isNull(subBusinessAttr)) {
                                        continue;
                                    }
                                    if (Objects.equals(item.getFieldType(), FieldTypeEnum.COMBO.getType())) {
                                        // 下拉框转换成规范格式
                                        JSONObject subCombo = new JSONObject();
                                        subCombo.put(StringConstant.TEXT, subData.getString(subBusinessAttr.getAttr()));
                                        subCombo.put(StringConstant.VALUE, subData.getString(subBusinessAttr.getAttr()));
                                        subObj.put(item.getAttr(), subCombo);
                                    }else {
                                        subObj.put(item.getAttr(), subData.getString(subBusinessAttr.getAttr()));
                                    }

                                }
                                if (subObj.size() > 0) {
                                    subArray.add(subObj);
                                }
                            }
                            data.put(fieldAttrEntity.getAttr(), subArray);
                            break;
                        default:
                            data.put(fieldAttrEntity.getAttr(), informationData.getString(attr));
                            break;
                    }
                }
            }

            enterpriseDetailGetVO.setData(data);
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return enterpriseDetailGetVO;
    }

    @Override
    public FineClueUserListVO getDepUserList(FineClueUserDTO fineClueUserDTO) throws XbbException {
        FineClueUserListVO fineClueUserListVO = new FineClueUserListVO();
        String corpid = fineClueUserDTO.getCorpid();
        Long deptId = fineClueUserDTO.getDepartmentId();
        UserVO loginUser = fineClueUserDTO.getLoginUser();
        Set<String> permSet = loginUser.getPermSet();
        String s = JSONObject.toJSONString(permSet);
        if (permSet.contains(ProPermissionAliasEnum.SOUKE_EDIT.getAlias())){
            fineClueUserListVO.setPermission(1);
        }else {
            fineClueUserListVO.setPermission(0);
        }

        List<FineClueUserVO> userVOList = new ArrayList<>();
        try {
            UserListDTO userListDTO = new UserListDTO();
            BeanUtil.copyProperties(fineClueUserDTO, userListDTO);
            userListDTO.setDepartmentId(deptId);
            UserListVO userListVO = userService.list(userListDTO);
            List<UserVO> userList = userListVO.getUserList();

            Set<String> userIdIn = new HashSet<>();
            userList.forEach(item -> userIdIn.add(item.getUserId()));
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.LIST_SELECT_TYPE_STAFF,BasicConstant.ONE);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<FineClueUserEntity> fineClueUserEntityList = fineClueUserModel.findEntitys(param);

            Map<String, FineClueUserEntity> userEntityMap = new HashMap<>(fineClueUserEntityList.size());
            fineClueUserEntityList.forEach((item) -> userEntityMap.put(item.getUserId(), item));
            userList.forEach(item -> {
                String userId = item.getUserId();
                FineClueUserVO fineClueUserVO = new FineClueUserVO();
                BeanUtil.copyProperties(item, fineClueUserVO);
                FineClueUserEntity entity = userEntityMap.get(userId);
                //前端坐席批量设置需要
                fineClueUserVO.setId(item.getId().longValue());
                if (entity != null) {
                    fineClueUserVO.setStaff(entity.getStaff());
                    fineClueUserVO.setClueUseNum(entity.getClueUseNum());
                    fineClueUserVO.setClueUseType(entity.getClueUseType());
                } else {
                    fineClueUserVO.setStaff(BasicConstant.ZERO);
                }
                userVOList.add(fineClueUserVO);
            });

            fineClueUserListVO.setPageHelper(userListVO.getPageHelper());
            fineClueUserListVO.setUserList(userVOList);
        } catch (XbbException e) {
            LOG.error("获取部门信息失败" + e.getMessage());
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
        }

        return fineClueUserListVO;
    }

    @Override
    public FineClueMsgVO batchUpdateUserStaff(FineClueUpdateListDTO fineClueUpdateListDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        List<String> userIdList = fineClueUpdateListDTO.getUserIdList();
        Integer staff = fineClueUpdateListDTO.getStaff();
        String corpid = fineClueUpdateListDTO.getCorpid();
        String userName = fineClueUpdateListDTO.getLoginUserName();
        CompanyEntity company = companyModel.getByKey(corpid);
        String companyName = company.getCorpName();
        List<UserEntity> userEntityList = userModel.findEntitysByUserIds(userIdList, corpid);
        Map<String, String> usernameMap = new HashMap<>();
        userEntityList.forEach(user -> {
            usernameMap.put(user.getUserId(), user.getName());
        });
        //如果是开启坐席，查询是否会超过总数
        if (Objects.equals(staff, BasicConstant.ONE)) {
            FineClueCompanyEntity companyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueComboEnum.FINE_CLUE.getCode());
            if (companyEntity == null) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280002);
            }
            String registerCorpid = companyEntity.getRegisterCorpid();

            Map<String, Object> param = new HashMap<>();
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.LIST_SELECT_TYPE_STAFF, BasicConstant.ONE);
            Integer entitysCount = fineClueUserModel.getEntitysCount(param);

            param.clear();
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("userIdIn", userIdList);
            param.put(StringConstant.LIST_SELECT_TYPE_STAFF, BasicConstant.ONE);
            List<FineClueUserEntity> fineClueUserModelEntitys = fineClueUserModel.findEntitys(param);
            //把已开启坐席的用户id去除
            fineClueUserModelEntitys.forEach(e -> {
                userIdList.removeIf(u -> Objects.equals(u, e.getUserId()));
            });
            int addUserSize = userIdList.size();
            if (Objects.equals(BasicConstant.ZERO,addUserSize)) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280010);
            }
            //想要开启的坐席数
            int count = entitysCount + addUserSize;
            Integer useCount = companyEntity.getUseCount();
            //已开启的坐席数+想要开启的坐席数 > 150（总坐席数）
            if (count > useCount) {
                //总数大于注册上限数
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280001);
            }
            //判断是否走注册流程
            Long registerCount = companyEntity.getRegisterCount();
            //i为剩余注册量
            int i = useCount - registerCount.intValue();
            //还可以走注册的userId
            Set<String> registerList = new HashSet<>();
            //走更新替换的userId
            Set<String> replaceSet = new HashSet<>();
            subList(userIdList, i, registerList, replaceSet);
            //走注册新用户
            if (CollectionsUtil.isNotEmpty(registerList)) {
                for (String s : registerList) {
                    String uid = UUID.randomUUID().toString();
                    //精线索开通
                    String content = registerCorpid + ":" + uid;
                    String projectName = ProBaseConfig.getProjectName();
                    String envName = "";
                    //打通账号测试环境公司id做区分
                    if (projectName.startsWith("xbbProTest")){
                        //截取环境名，xbbProTest从Test处取值
                        envName = projectName.substring(6);
                        content = envName + corpid + ":" + uid;
                    }
                    JSONObject object = new JSONObject();
                    String resultContent = FineClueUtil.AESUrlSafeEncrypt(content, proBaseConfig.getFineClueKey(), "ECB");
                    object.put("userName", usernameMap.get(s));
                    object.put("companyName", companyName);
                    object.put("content", resultContent);
                    object.put("monthlyLeads", -1);
                    String url = proBaseConfig.getFineClueUrl() + FineClueUrlConstant.REGISTER_URL;
                    JSONObject post = null;
                    try {
                        post = HttpHelper.httpPostDingtalk(url, object);
                    } catch (OApiException e) {
                        LOG.error("调用精线索接口失败fineClue参数:{},url:{}", object.toString());
                    }
                    if (Objects.isNull(post)) {
                        throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
                    }
                    Integer errcode = post.getInteger("errcode");
                    if (errcode == null || !errcode.equals(200)) {
                        LOG.error("调用精线索接口失败fineClue参数:{},url:{},post:{}", object.toString(), url, post);
                        throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
                    }
                    JSONObject data = post.getJSONObject(StringConstant.JSON_DATA);
                    String account = data.getString("account");
                    String password = data.getString("password");
                    LOG.info("fineAccount:" + data + "   registerCorpid:" + registerCorpid + "  uuid:" + uid);
                    // 获取是否为坐席
                    FineClueUserEntity fineClueUserEntity = fineClueUserModel.getByKey(corpid, s);
                    Integer staffInt = FineClueFormEnum.STAFFOPEN.getCode();
                    if (Objects.nonNull(fineClueUserEntity)) {
                        s = "";
                        staffInt = FineClueFormEnum.STAFFCLOSE.getCode();
                    }
                    FineClueUserEntity temp = new FineClueUserEntity();
                    temp.setUuid(uid);
                    temp.setCorpid(corpid);
                    temp.setRegisterCorpid(registerCorpid);
                    temp.setUserId(s);
                    temp.setClueUserId(account);
                    temp.setClueUserPassword(password);
                    temp.setClueUseNum(BasicConstant.TWO_HUNDRED);
                    temp.setClueUseType(FineClueFormEnum.EVERYDAY.getCode());
                    temp.setStaff(staffInt);
                    fineClueUserModel.insert(temp);
                    //走一次注册添加一次注册数
                    FineClueCompanyEntity entity = new FineClueCompanyEntity();
                    entity.setType(companyEntity.getType());
                    entity.setCorpid(corpid);
                    fineClueCompanyModel.autoincrementRegisterCount(entity);
                }
            }
            //走更新替换
            if (CollectionsUtil.isNotEmpty(replaceSet)) {
                Map<String, Object> map = new HashMap<>();
                map.put(StringConstant.CORPID, corpid);
                map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                map.put(StringConstant.LIST_SELECT_TYPE_STAFF, FineClueFormEnum.STAFFCLOSE.getCode());
                List<FineClueUserEntity> fineUserEntityList = fineClueUserModel.findEntitys(map);
                if (fineUserEntityList.size()==0){
                    throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280006);
                }
                List<FineClueUserEntity> list = new ArrayList<>();
                List<String> replaceList = new ArrayList<>(replaceSet);
                // TODO 批量更新
                int replaceSize = 0;
                for (FineClueUserEntity fineClueUserEntity : fineUserEntityList) {
                    fineClueUserEntity.setCorpid(corpid);
                    fineClueUserEntity.setUserId(replaceList.get(replaceSize));
                    fineClueUserEntity.setStaff(FineClueFormEnum.STAFFOPEN.getCode());
                    fineClueUserEntity.setUpdateTime(DateTimeUtil.getInt());
                    list.add(fineClueUserEntity);
                    replaceSize ++;
                    if (replaceSize >= replaceList.size()){
                        break;
                    }
                }
                fineClueUserModel.updateBatch(list, corpid);
            }
            //开启坐席日志
            List<UserEntity> userEntitys = userModel.findEntitysByUserIds(userIdList, corpid);
            StringBuffer usersName = getUsersName(userEntitys);
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_OPEN_STAFF), userName,usersName);
            mongoLogHelp.saveLoggerByInsert(corpid, fineClueUpdateListDTO.getUserId(), userName, companyName, memo, userIdList.toString(), "", OperateModuleTypeEnum.SOUKE, OperateTypeEnum.OPEONSTAFF);

        } else if (Objects.equals(staff, 0)){
            String userId = "";
            //把userId置为""
            fineClueUserModel.batchUpdateStaff(corpid, userIdList, staff,userId);
            //关闭坐席日志
            List<UserEntity> userEntitys = userModel.findEntitysByUserIds(userIdList, corpid);
            StringBuffer usersName = getUsersName(userEntitys);
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CLOSE_STAFF), userName,usersName);
            mongoLogHelp.saveLoggerByInsert(corpid, fineClueUpdateListDTO.getUserId(), userName, companyName, memo, userIdList.toString(), "", OperateModuleTypeEnum.SOUKE, OperateTypeEnum.CLOSESTAFF);
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        return fineClueMsgVO;
    }
    /**
        * @description: 拼接用户名
        * @param userEntityList 
        * @return java.lang.StringBuffer 
        * @author zhushuainan
        * @date 2022/03/29 09:47:59 
        */
    public StringBuffer getUsersName(List<UserEntity> userEntityList){
        StringBuffer names = new StringBuffer();
        int size = 1;
        for (UserEntity userEntity : userEntityList) {
            if (size < userEntityList.size()){
                names.append(userEntity.getName() + ",");
            } else {
                names.append(userEntity.getName());
            }
            size ++;
        }
        return names;
    }

    @Override
    public FineClueMsgVO openSoukeOrCompanyQueryTrial(FineClueOpenTrialDTO fineClueOpenTrialDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        FineClueComboEnum fineClueComboEnum;
        String alias = fineClueOpenTrialDTO.getAlias();
        if (CompanyConfigEnum.BUSINESS_SEARCH.getAlias().equals(alias)){
            fineClueComboEnum = FineClueComboEnum.COMPANY_QUERY;
        }else {
            fineClueComboEnum = FineClueComboEnum.FINE_CLUE;
        }

        String companyName = fineClueOpenTrialDTO.getCompanyName();
        String corpid = fineClueOpenTrialDTO.getCorpid();
        String userId = fineClueOpenTrialDTO.getUserId();

        // 销客提供的搜客功能未到期，不能使用精线索提供的搜客
        if (FineClueComboEnum.FINE_CLUE == fineClueComboEnum) {
            SearchCustomerCompanyEntity searchCustomerCompanyEntity = searchCustomerCompanyModel.getByCorpid(corpid, SoukeMealEnum.SOUKE.getType());
            if (Objects.nonNull(searchCustomerCompanyEntity) && searchCustomerCompanyEntity.getExtraExpiry() > DateTimeUtil.getInt()) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280012);
            }
        }

        FineClueCompanyEntity fineClueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, fineClueComboEnum.getCode());
        if (Objects.nonNull(fineClueCompanyEntity)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280013);
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        Integer count = fineClueCompanyModel.getEntitysCount(param);
        //账号已经打通过，不需要在调用账号打通接口
        if (count == 0 ){
            openAccount(corpid, userId, companyName, fineClueComboEnum);
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put(StringConstant.CORPID,corpid);
            map.put("userId",userId);
            List<UserEntity> entityList = userModel.findEntitys(map);
            UserEntity userEntity = entityList.get(0);
            String userName = userEntity.getName();
            FineClueCompanyEntity entity = new FineClueCompanyEntity();
            entity.setCorpid(corpid);
            entity.setUserId(userId);
            entity.setRegisterCorpid(corpid);
            entity.setType(fineClueComboEnum.getCode());
            entity.setCompanyName(companyName);
            entity.setUsername(userName);
            entity.setUseCount(0);
            long time = System.currentTimeMillis()+86400000*3;
            entity.setExtraExpiry(time/1000);
            if (Objects.equals(fineClueComboEnum,FineClueComboEnum.FINE_CLUE)){
                entity.setUseCount(150);
                entity.setRegisterCount(1L);
            }
            fineClueCompanyModel.insert(entity);
        }

        //初始化首页精线索菜单，管理中心应用
        if (fineClueComboEnum == FineClueComboEnum.FINE_CLUE){
            MenuInitDTO menuInitDTO = new MenuInitDTO();
            BeanUtil.copyProperties(fineClueOpenTrialDTO, menuInitDTO);
            initMenuHelp.menuInit(menuInitDTO);
        }else {
            //工商查询功能 开启关闭需要用到config_value字段
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(alias, corpid);
            if (Objects.isNull(companyConfigEntity)) {
                CompanyConfigEnum companyConfigEnum = CompanyConfigEnum.getByAlias(alias);
                companyConfigEntity = new CompanyConfigEntity(corpid, companyConfigEnum.getName(), companyConfigEnum.getAlias(), BasicConstant.IS_USE.toString());
                companyConfigModel.insert(companyConfigEntity);
            }
        }

        //新增一条销售机会
        AppModuleSaveDTO saveDTO = new AppModuleSaveDTO();
        BeanUtil.copyProperties(fineClueOpenTrialDTO, saveDTO);
        appModuleService.addSalesOpportunity(saveDTO);

        return fineClueMsgVO;
    }

    /***
     * @description: 账号打通接口
     * @param: corpid
     * @param: userId
     * @param: companyName
     * @param: fineClueComboEnum
     * @return: void
     * @author: zhushuainan
     * @date: 2021/12/23
     */
    private void openAccount(String corpid, String userId, String companyName, FineClueComboEnum fineClueComboEnum) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        String userName = userEntity.getName();
        FineClueCompanyEntity entity = new FineClueCompanyEntity();
        entity.setCorpid(corpid);
        entity.setUserId(userId);
        entity.setRegisterCorpid(corpid);
        entity.setType(fineClueComboEnum.getCode());
        entity.setCompanyName(companyName);
        entity.setUsername(userName);
        entity.setUseCount(0);
        long time = System.currentTimeMillis()+86400000*3;
        entity.setExtraExpiry(time/1000);
        //账号打通
        String uid = UUID.randomUUID().toString();
        String content = corpid + ":" + uid;
        String projectName = ProBaseConfig.getProjectName();
        String envName = "";
        //打通账号测试环境公司id做区分
        if (projectName.startsWith("xbbProTest")){
            //截取环境名，xbbProTest从Test处取值
            envName = projectName.substring(6);
            content = envName + corpid + ":" + uid;
        }
        JSONObject object = new JSONObject();
        String resultContent = FineClueUtil.AESUrlSafeEncrypt(content, proBaseConfig.getFineClueKey(), "ECB");
        object.put("userName", userName);
        object.put("companyName", companyName);
        object.put("content", resultContent);
        object.put("monthlyLeads", -1);
        String url = proBaseConfig.getFineClueUrl() + FineClueUrlConstant.REGISTER_URL;
        JSONObject post = null;
        try {
            post = HttpHelper.httpPostDingtalk(url, object);
        } catch (OApiException e) {
            LOG.error("调用精线索接口失败fineClue参数:{},url:{}", object.toString());
        }
        LOG.info("post:{}",post);
        Integer errcode = post.getInteger("errcode");
        if (errcode == null || !errcode.equals(200)) {
            LOG.error("调用精线索接口失败fineClue参数:{},url:{},post:{}", object.toString(),url,post);
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
        }
        JSONObject data = post.getJSONObject(StringConstant.JSON_DATA);
        String account = data.getString("account");
        String password = data.getString("password");
        FineClueUserEntity temp = new FineClueUserEntity();
        temp.setUuid(uid);
        temp.setCorpid(corpid);
        temp.setRegisterCorpid(corpid);
        temp.setUserId(userId);
        temp.setClueUserId(account);
        temp.setClueUserPassword(password);
        temp.setClueUseNum(100);
        temp.setClueUseType(1);
        temp.setStaff(1);
        fineClueUserModel.insert(temp);
        if (fineClueComboEnum == FineClueComboEnum.FINE_CLUE) {
            entity.setUseCount(150);
            entity.setRegisterCount(1L);
        }
        entity.setType(fineClueComboEnum.getCode());
        fineClueCompanyModel.insert(entity);
    }

    @Override
    public FineClueMsgVO addUseDosageRecord(FineClueCustomerDataDTO fineClueCustomerDataDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        JSONArray objectArray = fineClueCustomerDataDTO.getData();
        JSONObject object = objectArray.getJSONObject(0);
        String companyName = object.getString("companyName");
        String id = object.getString("id");
        //phone对应fineUser表中的clueUserId
        String clueUserId = fineClueCustomerDataDTO.getPhone();
        Map<String, Object> map = new HashMap<>();
        map.put("clueUserId",clueUserId);
        map.put("start",0);
        map.put("pageNum",1);
        List<FineClueUserEntity> entitys = fineClueUserModel.findEntitys(map);
        FineClueUserEntity clueUserEntity = entitys.get(0);
        String userId = clueUserEntity.getUserId();
        String corpid = clueUserEntity.getCorpid();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("userID",userId);
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity==null){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        FineClueConsumptionEntity fineClueConsumptionEntity = new FineClueConsumptionEntity(corpid, userId, null, null, null, id, fineClueCustomerDataDTO.getOperateTime());
        fineClueConsumptionEntity.setStatus(FineClueStatusEnum.UNLOCK.getCode());
        fineClueConsumptionEntity.setSource(ExternalDataSourceEnum.FINE_CLUE.getType());
        fineClueConsumptionModel.insert(fineClueConsumptionEntity);

        String name = userEntity.getName();
//        if (useDosage==1){
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_UNLOCKCONTACTINFO), name);
            mongoLogHelp.saveLoggerByInsert(corpid, userId, name, companyName, memo, id, "", OperateModuleTypeEnum.SOUKE, OperateTypeEnum.UNLOCKCONTACTINFO);
//        }
        return fineClueMsgVO;
    }

    @Override
    public EnterpriseDetailGetVO enterpriseGetList(EnterpriseDetailGetDTO enterpriseDetailGetDTO) throws XbbException {
        EnterpriseDetailGetVO enterpriseDetailGetVO = new EnterpriseDetailGetVO();
        String keyword = enterpriseDetailGetDTO.getKeyword();
        String corpid = enterpriseDetailGetDTO.getCorpid();
        String userId = enterpriseDetailGetDTO.getUserId();
        // 查看是否能使用精线索的工商查询
        FineClueCompanyEntity clueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.BUSINESS.getType());
        if (Objects.isNull(clueCompanyEntity)){
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280009);
        }
        if (clueCompanyEntity.getExtraExpiry() < DateUtil.getInt()) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280008);
        }
        //模板中心工商查询未开启
        CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.BUSINESS_SEARCH.getAlias(), corpid);
        if (Objects.nonNull(companyConfigEntity) && Objects.equals(companyConfigEntity.getConfigValue(),0)) {
                throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280014);
        }

        FineClueUserEntity clueUserEntity = fineClueUserModel.getByKey(corpid, userId);
        //如果是非坐席账户
        if (Objects.isNull(clueUserEntity)) {
            clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
        }
        if (Objects.isNull(clueUserEntity)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280008);
        }
        try {
            keyword = URLEncoder.encode(keyword, "utf-8");
        } catch (UnsupportedEncodingException e) {
            keyword = null;
        }
        if (Objects.isNull(keyword)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280002);
        }
        String sign = fineClueHelp.getSign(clueUserEntity.getRegisterCorpid(), clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword() ,enterpriseDetailGetDTO.getPlatform());
        //模糊查企业
        JSONObject baseInfo = fineClueHelp.fuzzySearchEnterprise(sign, keyword);
        if(Objects.isNull(baseInfo)){
            JSONObject jsonObject = new JSONObject();
            JSONArray resultJsonArray = new JSONArray();
            jsonObject.put("items", resultJsonArray);
            enterpriseDetailGetVO.setData(jsonObject);
            return enterpriseDetailGetVO;
//            throw new XbbException(ErrorCodeEnum.API_ERROR_280002);
        }
        JSONArray jsonArray = baseInfo.getJSONArray(StringConstant.JSON_DATA);
        if (CollectionsUtil.isEmpty(jsonArray)) {
            JSONObject jsonObject = new JSONObject();
            JSONArray resultJsonArray = new JSONArray();
            jsonObject.put("items", resultJsonArray);
            enterpriseDetailGetVO.setData(jsonObject);
            return enterpriseDetailGetVO;
//            throw new XbbException(ErrorCodeEnum.API_ERROR_280002);
        }
        JSONArray resultJsonArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            JSONObject temp = new JSONObject();
            temp.put("PID", object.getString("pid"));
            temp.put("ENTNAME", object.getString("entName"));
            resultJsonArray.add(temp);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("items", resultJsonArray);
        enterpriseDetailGetVO.setData(jsonObject);
        return enterpriseDetailGetVO;
    }

    @Override
    public FineClueConsumptionVO getFineClueConsumption(FineClueConsumptionDTO fineClueConsumptionDTO) throws XbbException {
        FineClueConsumptionVO fineClueConsumptionVO = new FineClueConsumptionVO();
        String corpid = fineClueConsumptionDTO.getCorpid();
        FineClueUserEntity clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
        if (clueUserEntity == null){
            throw new XbbException((FineClueErrorCodeEnum.API_ERROR_280002));
        }
        String sign = fineClueHelp.getSign(clueUserEntity.getRegisterCorpid(), clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword() ,fineClueConsumptionDTO.getPlatform());
        //从三方获取套餐总用量信息
        JSONObject baseInfo = fineClueHelp.getMealConsumption(sign);
        if (Objects.isNull(baseInfo)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280002);
        }
        JSONObject jsonObject = baseInfo.getJSONObject(StringConstant.JSON_DATA);
        LOG.info("***********jsonObject:{},sign:{}",jsonObject,sign);
        //
        String total = BasicConstant.ZERO_STRING;
        String monthUsed = BasicConstant.ZERO_STRING;
        String dayUsed = BasicConstant.ZERO_STRING;
        String intervalTotal = BasicConstant.ZERO_STRING;
        String intervalUsed = BasicConstant.ZERO_STRING;
        if (Objects.nonNull(jsonObject)) {
            total = jsonObject.containsKey("total") ? jsonObject.getString("total") : BasicConstant.ZERO_STRING;
            monthUsed = jsonObject.containsKey("used") ? jsonObject.getString("used") : BasicConstant.ZERO_STRING;
            dayUsed = jsonObject.containsKey("dayUsed") ? jsonObject.getString("dayUsed") : BasicConstant.ZERO_STRING;
            intervalTotal = jsonObject.containsKey("intervalTotal") ? jsonObject.getString("intervalTotal") : BasicConstant.ZERO_STRING;
            intervalUsed = jsonObject.containsKey("intervalUsed") ? jsonObject.getString("intervalUsed") : BasicConstant.ZERO_STRING;
        }
        fineClueConsumptionVO.setTotal(total);
        fineClueConsumptionVO.setUsed(monthUsed);
        //获取套餐有效期、套餐使用人数
        FineClueCompanyEntity clueCompanyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.FINE_CLUE.getType());
        if(clueCompanyEntity == null){
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280002);
        }
        fineClueConsumptionVO.setExtraExpiry(clueCompanyEntity.getExtraExpiry());
        HashMap<String, Object> map = new HashMap<>();
        map.put(StringConstant.CORPID,fineClueConsumptionDTO.getCorpid());
        map.put(StringConstant.LIST_SELECT_TYPE_STAFF,1);
        map.put("del",0);
        Integer count = fineClueUserModel.getEntitysCount(map);
        fineClueConsumptionVO.setUseNum(count + "/" + clueCompanyEntity.getUseCount());

        //公司本月总消耗量
//        int amount = fineClueHelp.getUseNumber(corpid, null, BasicConstant.TWO);
        fineClueConsumptionVO.setMonthTotalCompareTotal(monthUsed+"/"+fineClueConsumptionVO.getTotal());
        //公司本日总消耗量
//        int amount2 = fineClueHelp.getUseNumber(corpid, null, BasicConstant.ONE);
        fineClueConsumptionVO.setDayUsed(dayUsed);
        // 总消耗量/总线索量
        fineClueConsumptionVO.setIntervalUsedCompareintervalTotal(intervalUsed + "/" + intervalTotal);
        return fineClueConsumptionVO;
    }

    @Override
    public FineClueMsgVO releaseClue(FineClueClueReleaseDTO fineClueClueReleaseDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        String corpid = fineClueClueReleaseDTO.getCorpid();
        List<String> ids = fineClueClueReleaseDTO.getIds();
        if (CollectionsUtil.isEmpty(ids)) {
            return fineClueMsgVO;
        }
        FineClueUserEntity clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
        if (clueUserEntity == null){
            throw new XbbException((FineClueErrorCodeEnum.API_ERROR_280002));
        }
        // 修改用量表状态
        fineClueConsumptionModel.updateStatusByPids(corpid, ids, FineClueStatusEnum.RELEASE.getCode(), ExternalDataSourceEnum.FINE_CLUE.getType());

        String sign = fineClueHelp.getSign(clueUserEntity.getRegisterCorpid(), clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword() , fineClueClueReleaseDTO.getPlatform());
        String baseInfoUrl = proBaseConfig.getFineClueUrl()+FineClueUrlConstant.FINECLUECLUERELEASE_URL+"?sign="+sign;

        int count = ids.size();
        int start = 0;
        int pageNum = 100;
        JSONObject request = new JSONObject();
        JSONObject baseInfo = null;
        for (; start <= count; start = start + pageNum) {
            int endIndex = (start + pageNum) <= count ? start + pageNum : count;
            List<String> pids = ids.subList(start, endIndex);
            request.clear();
            request.put("ids",pids);
            //调用第三方接口释放线索
            try {
                baseInfo = HttpHelper.httpPostDingtalk(baseInfoUrl, request);
            } catch (OApiException e) {
                LOG.error("精线索线索释放失败：fineUrl：{}", baseInfoUrl);
            }
        }
        return fineClueMsgVO;
    }

    @Override
    public FineClueUserSurplusUsageVO getSurplusUsage(FineClueUserSurplusUsageDTO fineClueUserSurplusUsageDTO) throws XbbException {
        FineClueUserSurplusUsageVO fineClueUserSurplusUsageVO = new FineClueUserSurplusUsageVO();
        String account = fineClueUserSurplusUsageDTO.getAccount();
        Map<String, Object> map = new HashMap<>();
        map.put("clueUserId",account);
        List<FineClueUserEntity> list = fineClueUserModel.findEntitys(map);
        FineClueUserEntity clueUserEntity = list.get(0);
        String corpid = clueUserEntity.getCorpid();
        String userId = clueUserEntity.getUserId();
        Integer type = clueUserEntity.getClueUseType();
        Integer clueUseNum = clueUserEntity.getClueUseNum();
        int count = fineClueHelp.getUseNumber(corpid, userId, type);
        int surplusNum = Math.max(clueUseNum - count, BasicConstant.ZERO);
        fineClueUserSurplusUsageVO.setUserSurplusUsage(String.valueOf(surplusNum));
        return fineClueUserSurplusUsageVO;
    }

    @Override
    public FineClueMsgVO openOfficialVersion(FineClueOfficiallyOpenDTO fineClueOfficiallyOpenDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        //推送一条销售机会
        AppModuleSaveDTO saveDTO = new AppModuleSaveDTO();
        BeanUtil.copyProperties(fineClueOfficiallyOpenDTO, saveDTO);
        appModuleService.addSalesOpportunity(saveDTO);

        return fineClueMsgVO;
    }

    @Override
    public FineCluePageGetVO getFineCluePage(FineCluePageGetDTO fineCluePageGetDTO) throws XbbException {
        FineCluePageGetVO fineCluePageGetVO = new FineCluePageGetVO();
        String corpid = fineCluePageGetDTO.getCorpid();
        String pageName = fineCluePageGetDTO.getPageName();
        Boolean isNewAdd = fineCluePageGetDTO.getIsNewAdd();

        FineCluePageRouteEnum routeEnum = FineCluePageRouteEnum.getByRoute(pageName);
        if (Objects.isNull(routeEnum)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280005);
        }

        String userId = fineCluePageGetDTO.getUserId();
        // 是否为工商查询
        Boolean isIndustSearch;
        String pId = fineCluePageGetDTO.getCompanyId();

        // 获取座席账号
        FineClueUserEntity clueUserEntity = fineClueUserModel.getUserByStaff(corpid, userId, BasicConstant.ONE);
        if (Objects.isNull(clueUserEntity)) {
            isIndustSearch = true;
            clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
        } else {
            isIndustSearch = Objects.nonNull(isNewAdd) && isNewAdd;
        }
        if (Objects.isNull(clueUserEntity)){
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280002);
        }

        JSONObject data = fineClueHelp.getRouteData(pId, clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword(), routeEnum, isIndustSearch,fineCluePageGetDTO.getPlatform());
        if (Objects.isNull(data)) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280007);
        }
        fineCluePageGetVO.setData(data);
        return fineCluePageGetVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FineClueMsgVO batchUpdateUserDosage(FineClueUpdateDosageDTO fineClueUpdateDosageDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        Integer num = fineClueUpdateDosageDTO.getNum();
        List<String> userIdList = fineClueUpdateDosageDTO.getUserIdList();
        String corpid = fineClueUpdateDosageDTO.getCorpid();
        Integer type = fineClueUpdateDosageDTO.getType();
        Map<String, Object> param = new HashMap<>();
        param.put(StringConstant.CORPID, corpid);
        param.put("userIdIn", userIdList);
        param.put(StringConstant.LIST_SELECT_TYPE_STAFF, 1);
        List<FineClueUserEntity> clueUserList = fineClueUserModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(clueUserList) || userIdList.size() > clueUserList.size()) {
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280004);
        }
        fineClueUserModel.batchUpdateDosage(corpid, userIdList, type, num);

        return fineClueMsgVO;
    }

    @Override
    public FineClueMsgVO transitionCustomerOrClue(FineClueCustomerDataDTO clueCustomerDataDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        String tag = clueCustomerDataDTO.getTag();
        //如果是解锁操作，记录一条用量日志
        if (Objects.equals(tag,"UNLOCK")){
            addUseDosageRecord(clueCustomerDataDTO);
            return fineClueMsgVO;
        }
        String value = paasRedisHelper.getValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, tag);
        if (StringUtil.isEmpty(value)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        FineClueRedisTypeDTO fineClueRedisTypeDTO = JSONObject.parseObject(value,FineClueRedisTypeDTO.class);
        JSONObject formInfo = fineClueRedisTypeDTO.getData();
        List<String> errorPidList = new ArrayList<>();
        JSONArray jsonArray = clueCustomerDataDTO.getData();
        Integer type = formInfo.getInteger("type");
        String corpid = formInfo.getString(StringConstant.CORPID);
        Long appId = formInfo.getLong("appId");
        Long menuId = formInfo.getLong("menuId");
        Long formId = formInfo.getLong("formId");
        String userId = formInfo.getString("userId");
        LOG.info("fineClueToCustomer dto:{} data:{},formInfo:{}", fineClueRedisTypeDTO, jsonArray, formInfo);
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        JSONArray ownerId = formInfo.getJSONArray("ownerId");

        //如果当前用户的用量小于领取的量，把所有的数据返回回去，当做全部领取失败处理
        FineClueUserSurplusUsageDTO fineClueUserSurplusUsageDTO = new FineClueUserSurplusUsageDTO();
        fineClueUserSurplusUsageDTO.setAccount(clueCustomerDataDTO.getPhone());
        FineClueUserSurplusUsageVO surplusUsage = getSurplusUsage(fineClueUserSurplusUsageDTO);
        String userSurplusUsage = surplusUsage.getUserSurplusUsage();
        int size = jsonArray.size();
        if (size > Integer.parseInt(userSurplusUsage)){
            fineClueMsgVO.setIsAllError(true);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject clueObj = jsonArray.getJSONObject(i);
                String id = clueObj.getString("id");
                errorPidList.add(id);
            }
            fineClueMsgVO.setErrorPidList(errorPidList);
            return fineClueMsgVO;
        }

        List<ReturnUserAndDepartmentPojo> ownerIdPojo = new ArrayList<>();
        if (ownerId!=null&&ownerId.size()>0){
            for (int i=0;i<ownerId.size();i++){
                JSONObject jsonObject = ownerId.getJSONObject(i);
                ReturnUserAndDepartmentPojo pojo = new ReturnUserAndDepartmentPojo();
                pojo.setId(jsonObject.getString("id"));
                pojo.setName(jsonObject.getString("name"));
                ownerIdPojo.add(pojo);
            }
        }
        if (jsonArray.size() == 0) {
            LOG.error("精线索接口data数据为空");
            throw new XbbException(FineClueErrorCodeEnum.API_ERROR_280003);
        }
        // pid集合
        Set<String> pidIn = new HashSet<>();
        FineClueToCustomerEnum fineClueToCustomerEnum = FineClueToCustomerEnum.getByType(type);
        //把每条线索的id和companyName存到redis中
        String httpHeader = fineClueRedisTypeDTO.getHttpHeader();
        String userName = fineClueRedisTypeDTO.getLoginUserName();
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        object.put(StringConstant.CORPID, corpid);
        object.put("userId", userId);
        object.put("httpHeader", httpHeader);
        object.put("userName",userName);
        object.put("tag",tag);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject clueObj = jsonArray.getJSONObject(i);
            String id = clueObj.getString("id");
            String companyName = clueObj.getString("companyName");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",id);
            jsonObject.put("companyName",companyName);
            array.add(jsonObject);
            pidIn.add(id);
        }
        object.put("list", array);
        String phone = clueCustomerDataDTO.getPhone();
        String serialNumber = clueCustomerDataDTO.getSerialNumber();
        String key = phone + "____" + serialNumber;
        paasRedisHelper.setValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, key, object, RedisTimeConstant.TEN_MINUTES);
        List<FineClueConsumptionEntity> insertConsumpList = new ArrayList<>();
        List<FineClueConsumptionEntity> updateConsumpList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("pidIn",pidIn);
        param.put("source",ExternalDataSourceEnum.FINE_CLUE.getType());
        param.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
        List<FineClueConsumptionEntity> consumptionList = fineClueConsumptionModel.findEntitys(param);
        HashMap<String, FineClueConsumptionEntity> consumptionMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(consumptionList)){
            consumptionList.forEach(item -> consumptionMap.put(item.getPid(),item));
        }
        // 处理三方推送的数据
        saveClue(jsonArray, consumptionMap, fineClueRedisTypeDTO, fineClueToCustomerEnum, ownerId,
                ownerIdPojo, paasFormExplainEntity, formInfo, insertConsumpList, updateConsumpList, errorPidList, clueCustomerDataDTO);
        LOG.info("fineClueMsgVO:"+fineClueMsgVO);
        return fineClueMsgVO;
    }

    /**
        * @description: 处理三方推送的线索
        * @param
        * @return void
        * @author zhushuainan
        * @date 2022/11/03 10:07:17
        */
    public void saveClue(JSONArray jsonArray, HashMap<String, FineClueConsumptionEntity> consumptionMap,FineClueRedisTypeDTO fineClueRedisTypeDTO,
                         FineClueToCustomerEnum fineClueToCustomerEnum, JSONArray ownerId, List<ReturnUserAndDepartmentPojo> ownerIdPojo, PaasFormExplainEntity paasFormExplainEntity,
                         JSONObject formInfo, List<FineClueConsumptionEntity> insertConsumpList, List<FineClueConsumptionEntity> updateConsumpList, List<String> errorPidList, FineClueCustomerDataDTO clueCustomerDataDTO) {
        Integer type = formInfo.getInteger("type");
        String corpid = formInfo.getString(StringConstant.CORPID);
        Long appId = formInfo.getLong("appId");
        Long menuId = formInfo.getLong("menuId");
        Long formId = formInfo.getLong("formId");
        String userId = formInfo.getString("userId");
        TransferClueParamPOJO transferClueParamPOJO = new TransferClueParamPOJO();
        String redisKey = corpid + "_" + clueCustomerDataDTO.getTag();
        Runnable runnable = () -> {
            CountDownLatch countDownLatch = new CountDownLatch(jsonArray.size());
            FineClueServiceImpl fineClueService = SpringUtil.getBean(FineClueServiceImpl.class);
            // 遍历三方data，把数据存到xbb表单里
            for (int i = 0; i < jsonArray.size(); i++) {
                fineClueService.asynTransformClue(jsonArray, i, consumptionMap, fineClueRedisTypeDTO, fineClueToCustomerEnum, ownerId, ownerIdPojo, paasFormExplainEntity, formInfo,
                        insertConsumpList, updateConsumpList, errorPidList, clueCustomerDataDTO ,appId, menuId, formId, userId, corpid, countDownLatch);
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
            }
            // 批量插入用量表
            fineClueConsumptionModel.insertBatch(insertConsumpList);
            // 批量跟新用量表
            fineClueConsumptionModel.updateBatch(updateConsumpList, corpid);

            JSONObject result = new JSONObject();
            JSONObject callBackResult = new JSONObject();

            if (Objects.equals(jsonArray.size(), errorPidList.size())) {
                result.put("isAllError", true);
            } else {
                result.put("isAllError", false);
            }
            //存储转线索的任务状态 转成功的条数 线索总条数 转入的表单
            int successNum = jsonArray.size() - errorPidList.size();
            int falseNum = jsonArray.size() - successNum;
            transferClueParamPOJO.setSuccessNum(successNum);
            transferClueParamPOJO.setType(type);
            transferClueParamPOJO.setClueCount(jsonArray.size());
            transferClueParamPOJO.setFalseNum(falseNum);
            if (CollectionsUtil.isEmpty(ownerId)) {
                transferClueParamPOJO.setIsPublicSea(true);
            } else {
                transferClueParamPOJO.setIsPublicSea(false);
            }
            paasRedisHelper.setValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, redisKey, transferClueParamPOJO, RedisTimeConstant.TEN_MINUTES);
            //todo 调用三方接口推送数据
            FineClueUserEntity clueUserEntity = fineClueUserModel.getSingleUserByCorpid(corpid);
            if (clueUserEntity == null){
                LOG.error("The staffs are not available");
                return;
            }
            if (errorPidList.size()>0){
                LOG.info("errorPidList:{}",errorPidList.toString());
            }
            String sign = fineClueHelp.getSign(clueUserEntity.getRegisterCorpid(), clueUserEntity.getClueUserId(), clueUserEntity.getClueUserPassword() , null);
            result.put("errorPidList",errorPidList);
            callBackResult.put("serialNumber",clueCustomerDataDTO.getSerialNumber());
            callBackResult.put("result",result);
            JSONObject callBackInfo = null;
            callBackInfo = fineClueHelp.dataPushCallBack(callBackResult, sign);
            if (Objects.isNull(callBackInfo)){
                LOG.error("callBackInfo is null");
            }
        };
        runnable.run();

    }

    @Async("fineClueTransformThreadPool")
    public void asynTransformClue(JSONArray jsonArray, int i,HashMap<String, FineClueConsumptionEntity> consumptionMap,FineClueRedisTypeDTO fineClueRedisTypeDTO,
                                  FineClueToCustomerEnum fineClueToCustomerEnum, JSONArray ownerId, List<ReturnUserAndDepartmentPojo> ownerIdPojo, PaasFormExplainEntity paasFormExplainEntity,
                                  JSONObject formInfo, List<FineClueConsumptionEntity> insertConsumpList, List<FineClueConsumptionEntity> updateConsumpList, List<String> errorPidList, FineClueCustomerDataDTO clueCustomerDataDTO,
                                Long appId, Long menuId, Long formId, String userId, String corpid, CountDownLatch countDownLatch) {

        JSONObject clueObj = jsonArray.getJSONObject(i);

        /**
         * leadsStatus = "unLock"， # unLock 解锁， fellow 转客户，open 未转线索和没有转客户的线索
         */
        String leadsStatus = clueObj.getString("leadsStatus");
        // 状态全部改为小写
        leadsStatus =  leadsStatus.toLowerCase();
        String id = clueObj.getString("id");
        try {
            FineClueConsumptionEntity fineClueConsumptionEntity = consumptionMap.get(id);
            // 已绑定且未释放不处理。
            if (Objects.nonNull(fineClueConsumptionEntity) && Objects.nonNull(fineClueConsumptionEntity.getDataId()) && Objects.equals(fineClueConsumptionEntity.getStatus(), FineClueStatusEnum.UNLOCK.getCode())) {
                return;
            }
            JSONObject addObject = new JSONObject();
            FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
            BeanUtil.copyProperties(fineClueRedisTypeDTO, formDataAddDTO);
            switch (fineClueToCustomerEnum) {
                case CUSTOMER:
                    if (CollectionsUtil.isEmpty(ownerId)) {
                        addObject.put(CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
                    } else {
                        formDataAddDTO.setOwnerId(ownerIdPojo);
                    }
                    break;
                case CLUE:
                    if (CollectionsUtil.isEmpty(ownerId)) {
                        addObject.put(ClueEnum.IS_PUBLIC.getAttr(), 0);
                    } else {
                        formDataAddDTO.setOwnerId(ownerIdPojo);
                    }
                    break;
                default:
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
            }
            //组装默认值
            addDefaultValue(addObject, paasFormExplainEntity);
            // 推荐电话
            List<String> recommendPhoneList = new ArrayList<>();
            //组装精线索信息
            addObject.putAll(setCustomerData(clueObj, paasFormExplainEntity, paasFormExplainEntity.getBusinessType(), userId, recommendPhoneList));
            formDataAddDTO.setCorpid(corpid);
            formDataAddDTO.setFormId(formId);
            formDataAddDTO.setAppId(appId);
            formDataAddDTO.setMenuId(menuId);
            formDataAddDTO.setBusinessType(formInfo.getInteger("businessType"));
            formDataAddDTO.setSaasMark(formInfo.getInteger("saasMark"));
            formDataAddDTO.setDataList(addObject);
            formDataAddDTO.setDistributorMark(formInfo.getInteger("distributorMark"));
            formDataAddDTO.setPlatform(formInfo.getString("platform"));
            formDataAddDTO.setSerialNo("");
            formDataAddDTO.setUserId(userId);
            formDataAddDTO.setOwnerId(ownerIdPojo);
            formDataAddDTO.setFineCluePhone(recommendPhoneList);
            FormDataAddVO formDataAddVO = paasFormDataService.addByOnlyRepeatValidate(formDataAddDTO);
            Long dataId = formDataAddVO.getDataId();
            if (Objects.isNull(fineClueConsumptionEntity)) {
                fineClueConsumptionEntity = new FineClueConsumptionEntity(corpid, userId, fineClueToCustomerEnum.getCode(), formId, dataId, id, clueCustomerDataDTO.getOperateTime());
                fineClueConsumptionEntity.setStatus(FineClueStatusEnum.UNLOCK.getCode());
                fineClueConsumptionEntity.setSource(ExternalDataSourceEnum.FINE_CLUE.getType());
            } else {
                //更新绑定
                fineClueConsumptionEntity.setBusinessType(fineClueToCustomerEnum.getCode());
                fineClueConsumptionEntity.setFormId(formId);
                fineClueConsumptionEntity.setDataId(dataId);
            }
            if (Objects.isNull(fineClueConsumptionEntity.getId()) || Objects.equals(fineClueConsumptionEntity.getId(), 0L)) {
                insertConsumpList.add(fineClueConsumptionEntity);
            } else {
                updateConsumpList.add(fineClueConsumptionEntity);
            }
            // 过滤已领取的重复数据过滤掉
            consumptionMap.put(fineClueConsumptionEntity.getPid(), fineClueConsumptionEntity);
            LOG.info("formDataAddVO:", formDataAddVO);
            String name = fineClueRedisTypeDTO.getLoginUserName();
            String companyName = clueObj.getString("companyName");

            String businessTypeStr = "线索";
            if (fineClueToCustomerEnum == FineClueToCustomerEnum.CUSTOMER) {
                businessTypeStr = "客户";
            }
            //转成功记录日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CLUETRANSFERCUSTOMERORCLUE), name, companyName, businessTypeStr);

            mongoLogHelp.saveLoggerByInsert(corpid, userId, name, companyName, memo, id, fineClueRedisTypeDTO.getHttpHeader(), OperateModuleTypeEnum.SOUKE, OperateTypeEnum.CLUETRANSFERCUSTOMERORCLUE);

        } catch (XbbException e) {
            LOG.info("fineclue transforms XbbException：", e.getMsg());
            if (Objects.equals(leadsStatus, "open") || Objects.equals(leadsStatus, "unlock")) {
                errorPidList.add(id);
            }
        } catch (Exception e) {
            LOG.error("fineclue transforms Exception：", e);
            if (Objects.equals(leadsStatus, "open") || Objects.equals(leadsStatus, "unlock")) {
                errorPidList.add(id);
            }
        } finally {
            countDownLatch.countDown();
        }
    }
    @Override
    public FineClueMsgVO setTransitionInfo(FineClueRedisTypeDTO fineClueRedisTypeDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        String corpid = fineClueRedisTypeDTO.getCorpid();
        String userId = fineClueRedisTypeDTO.getUserId();
        String tag = fineClueRedisTypeDTO.getTag();
        JSONObject jsonObject = fineClueRedisTypeDTO.getData();
        paasRedisHelper.setValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, tag, fineClueRedisTypeDTO, RedisTimeConstant.TEN_MINUTES);
        TransferClueParamPOJO transferClueParamPOJO = new TransferClueParamPOJO();
        transferClueParamPOJO.setFinish(false);
        String redisKey = corpid + "___" + tag;
        paasRedisHelper.setValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, redisKey, transferClueParamPOJO, RedisTimeConstant.TEN_MINUTES);

        // 用量是否超出
        FineClueUserEntity fineClueUserEntity = fineClueUserModel.getByKey(corpid, userId);
        boolean receiveFlag = false;
        if (Objects.nonNull(fineClueUserEntity)) {
            int count = fineClueHelp.getUseNumber(corpid, userId, fineClueUserEntity.getClueUseType());
            receiveFlag = count < fineClueUserEntity.getClueUseNum();
        }
        int receive = receiveFlag ? BasicConstant.ONE : BasicConstant.ZERO;
        fineClueMsgVO.setReceiveFlag(receive);
        return fineClueMsgVO;
    }

    private void subList(List<String> source, int index, Set<String> registerList, Set<String> replaceList) {
        if (CollectionsUtil.isEmpty(source)) {
            return;
        }
        for (int i = 0; i < source.size(); i++) {
            if (i < index) {
                registerList.add(source.get(i));
            } else {
                replaceList.add(source.get(i));
            }
        }
    }

    private Long stringToLongTime(String dateString) {
        if (StringUtil.isEmpty(dateString)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Long time = simpleDateFormat.parse(dateString).getTime() / 1000;
            return time;
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * @Author mingliang
     * @Description 获得经营开始时间与结束时间
     * @Date 2021/10/29 15:10
     **/
    private static JSONObject getOperatingPeriod(String operatingPeriod) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(operatingPeriod)){
            return jsonObject;
        }
        Long operatingPeriodStart = null;
        Long operatingPeriodEnd = null;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            operatingPeriodStart = null;
            operatingPeriodEnd = null;
            if (operatingPeriod.length() >= 10) {
                String operatingPeriodStartString = operatingPeriod.substring(0, 10);
                operatingPeriodStart = simpleDateFormat.parse(operatingPeriodStartString).getTime() / 1000;
            }
            if (operatingPeriod.length() >= 21) {
                String operatingPeriodEndString = operatingPeriod.substring(11, 21);
                operatingPeriodEnd = simpleDateFormat.parse(operatingPeriodEndString).getTime() / 1000;
            }
        } catch (ParseException e) {
            return jsonObject;
        }
        jsonObject.put("operatingPeriodStart", operatingPeriodStart);
        jsonObject.put("operatingPeriodEnd", operatingPeriodEnd);
        return jsonObject;
    }


    /**
     * @Author mingliang
     * @Description 设置精线索的客户名称，简称，地址，电话，精线索id
     * @Date 2021/11/8 17:33
     * @param jsonObject
     **/
    private JSONObject setCustomerData(JSONObject jsonObject,PaasFormExplainEntity paasFormExplainEntity,Integer businessType,String userId, List<String> recommendPhoneList) {
        JSONObject customer = new JSONObject();
        String id = jsonObject.getString("id");
        //公司名称
        String companyName = jsonObject.getString("companyName");
        //公司简称
        String legalRepresentative = jsonObject.getString("legalRepresentative");
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
            customer.put(CustomerManagementEnum.NAME.getAttr(), companyName);
            customer.put(CustomerManagementEnum.NAME_SHORT.getAttr(), legalRepresentative);
            customer.put(CustomerManagementEnum.IS_ARCHIVED.getAttr(), 2);
            customer.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0);
            customer.put(CustomerManagementEnum.CREATOR.getAttr(), userId);
        }else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
            customer.put(ClueEnum.COMPANY_NAME.getAttr(), companyName);
            customer.put(ClueEnum.CONTACT.getAttr(), legalRepresentative);
            customer.put(ClueEnum.IS_ARCHIVED.getAttr(), 2);
            customer.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), 0);
            customer.put(ClueEnum.CREATOR_ID.getAttr(), userId);
        }

        String registeredAddress = jsonObject.getString("registeredAddress");
        JSONObject phoneNumber = jsonObject.getJSONObject("phoneNumber");
        if (phoneNumber != null) {
            JSONArray qq = phoneNumber.getJSONArray("qq");
            JSONArray other = phoneNumber.getJSONArray("other");
            JSONArray mobile = phoneNumber.getJSONArray("mobile");
            JSONArray wechat = phoneNumber.getJSONArray("wechat");
            JSONArray fixedTelephone = phoneNumber.getJSONArray("fixedTelephone");
            JSONArray email = phoneNumber.getJSONArray("email");
            JSONArray fax = phoneNumber.getJSONArray("fax");


            String explains = paasFormExplainEntity.getExplains();
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, CustomerManagementEnum.PHONE.getAttr());
            FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
            List<? extends FieldAttrEntity> items = subForm.getItems();
            List<ItemPoJo> list = items.get(0).getItems();

            JSONArray xbbTel = new JSONArray();
            // 非推荐的联系有方式
            JSONArray noRecommendMobileList = new JSONArray();
            JSONArray noRecommendFixedTelList = new JSONArray();
            // 去重
            Set<String> addValueSet = new HashSet<>();

            // todo 下面代码需要优化@帅楠
            if (mobile != null && mobile.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("mobile").getName();
                Object value = getValue(list, name);
                for (Object e : mobile) {
                    /**
                     * mobile作类型判断，
                     * 原格式：mobile=[13455208848, 13038044620, 13969654607, 13723948250], #废弃
                     * 新格式：mobile=[{"info":"13455208848","recommend":true}], #2022年1月10日修改
                     */
                    String mobileStr;
                    if (e instanceof JSONObject) {
                        boolean recommend = ((JSONObject) e).getBoolean("recommend");
                        if (!recommend) {
                            noRecommendMobileList.add(e);
                            continue;
                        }
                        mobileStr = ((JSONObject) e).getString("info");
                    } else {
                        mobileStr = e.toString();
                    }
                    if (addValueSet.contains(mobileStr)) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", mobileStr);
                    xbbTel.add(temp);
                    addValueSet.add(mobileStr);
                    recommendPhoneList.add(mobileStr);
                }
            }
            if (fixedTelephone != null && fixedTelephone.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("fixedTelephone").getName();
                Object value = getValue(list, name);
                for (Object e : fixedTelephone) {
                    /**
                     * mobile作类型判断，
                     * 原格式：fixedTelephone=[0532-88257777, 0532-88257999], #废弃
                     * 新格式：fixedTelephone=[{"info":"0532-88257777","recommend":true}], #2022年1月10日修改
                     */
                    String mobileStr;
                    if (e instanceof JSONObject) {
                        boolean recommend = ((JSONObject) e).getBoolean("recommend");
                        if (!recommend) {
                            noRecommendFixedTelList.add(e);
                            continue;
                        }
                        mobileStr = ((JSONObject) e).getString("info");
                    } else {
                        mobileStr = e.toString();
                    }
                    if (addValueSet.contains(mobileStr)) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", mobileStr);
                    xbbTel.add(temp);
                    addValueSet.add(mobileStr);
                    recommendPhoneList.add(mobileStr);
                }
            }
            if (noRecommendMobileList.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("mobile").getName();
                Object value = getValue(list, name);
                for (Object e : mobile) {
                    /**
                     * mobile作类型判断，
                     * 原格式：mobile=[13455208848, 13038044620, 13969654607, 13723948250], #废弃
                     * 新格式：mobile=[{"info":"13455208848","recommend":true}], #2022年1月10日修改
                     */
                    String mobileStr;
                    if (e instanceof JSONObject) {
                        mobileStr = ((JSONObject) e).getString("info");
                    } else {
                        mobileStr = e.toString();
                    }
                    if (addValueSet.contains(mobileStr)) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", mobileStr);
                    xbbTel.add(temp);
                    addValueSet.add(mobileStr);
                }
            }
            if (noRecommendFixedTelList.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("fixedTelephone").getName();
                Object value = getValue(list, name);
                for (Object e : fixedTelephone) {
                    /**
                     * mobile作类型判断，
                     * 原格式：fixedTelephone=[0532-88257777, 0532-88257999], #废弃
                     * 新格式：fixedTelephone=[{"info":"0532-88257777","recommend":true}], #2022年1月10日修改
                     */
                    String mobileStr;
                    if (e instanceof JSONObject) {
                        mobileStr = ((JSONObject) e).getString("info");
                    } else {
                        mobileStr = e.toString();
                    }
                    if (addValueSet.contains(mobileStr)) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", mobileStr);
                    xbbTel.add(temp);
                    addValueSet.add(mobileStr);
                }
            }
            if (wechat != null && wechat.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("wechat").getName();
                Object value = getValue(list, name);
                for (Object e : wechat) {
                    if (addValueSet.contains(e.toString())) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", e);
                    xbbTel.add(temp);
                    addValueSet.add(e.toString());
                }
            }
            if (qq != null && qq.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("qq").getName();
                Object value = getValue(list, name);
                for (Object e : qq) {
                    if (addValueSet.contains(e.toString())) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", e);
                    xbbTel.add(temp);
                    addValueSet.add(e.toString());
                }
            }
            if (email != null && email.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("email").getName();
                Object value = getValue(list, name);
                for (Object e : email) {
                    if (addValueSet.contains(e.toString())) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", e);
                    xbbTel.add(temp);
                    addValueSet.add(e.toString());
                }
            }
            if (fax != null && fax.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("fax").getName();
                Object value = getValue(list, name);
                for (Object e : fax) {
                    if (addValueSet.contains(e.toString())) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", e);
                    xbbTel.add(temp);
                    addValueSet.add(e.toString());
                }
            }
            if (other != null && other.size() > 0) {
                String name = FineClueContactInfoEnum.getEnum("other").getName();
                Object value = getValue(list, name);
                for (Object e : other) {
                    if (addValueSet.contains(e.toString())) {
                        continue;
                    }
                    JSONObject temp = new JSONObject();
                    temp.put("text_1", value);
                    temp.put("text_2", e);
                    xbbTel.add(temp);
                    addValueSet.add(e.toString());
                }
            }
            // 插入联系方式总数50
            int maxSize = (BasicConstant.TWO_HUNDRED / BasicConstant.FOUR);
            List<Object> contactList = xbbTel.toJavaList(Object.class);
            if (contactList.size() > maxSize) {
                contactList = contactList.subList(BasicConstant.ZERO, maxSize);
            }
            customer.put(ContactEnum.PHONE.getAttr(), contactList);
            if (recommendPhoneList.size() > maxSize) {
                recommendPhoneList = recommendPhoneList.subList(BasicConstant.ZERO, maxSize);
            }
        }

        JSONObject contactAddress = searchCustomerHelp.changeAddress(registeredAddress);
        if (contactAddress == null) {
            contactAddress = new JSONObject();
            contactAddress.put("address", registeredAddress);
            contactAddress.put("province", "");
            contactAddress.put("city", "");
            contactAddress.put("district", "");
        }
        customer.put(ContactEnum.ADDRESS.getAttr(), contactAddress);
        return customer;
    }
    
    /*** 
     * @description: 获取explains中联系方式对应的value 
     * @param: list
 * @param: name 
     * @return: java.lang.Object 
     * @author: zhushuainan
     * @date: 2021/11/24 11:18
     * 思路：如果传过来的参数和用户编辑的类型匹配联系方式就放在匹配的，否则有其他的话就放其他，否则放在第一个
     */
    public Object getValue(List<ItemPoJo> list, String name){
        Boolean isMatch = false;
        Boolean isOther = false;
        int index = 0;
        int otherIndex = 0;
        for (ItemPoJo itemPoJo : list) {
            if (name.equals(itemPoJo.getText())){
                isMatch = true;
                ItemPoJo poJo = list.get(index);
                Object value = itemPoJo.getValue();
                return value;
            }
            if (itemPoJo.getText().equals("其他")){
                isOther = true;
                otherIndex = index;
            }
            index++;
        }
        if (isMatch == false && isOther == true){
            ItemPoJo itemPoJo = list.get(otherIndex);
            Object value = itemPoJo.getValue();
            return value;
        }
        return list.get(0).getValue();
    }

    /**
     * @Author mingliang
     * @Description 设置默认值
     * @Date 2021/11/8 16:29
     * @param addObject
     * @param explainEntity
     **/
    public void addDefaultValue(JSONObject addObject, PaasFormExplainEntity explainEntity) {
        Integer businessType = explainEntity.getBusinessType();
        String explains = explainEntity.getExplains();
        JSONArray jsonArrayExplain = JSONArray.parseArray(explains);
        for (int j = 0; j < jsonArrayExplain.size(); j++) {
            JSONObject jsonObjectExplain = jsonArrayExplain.getJSONObject(j);
            Integer fieldType = jsonObjectExplain.getInteger(FieldAttrConstant.FIELD_TYPE);
            String attr = jsonObjectExplain.getString("attr");
            JSONArray itemList = jsonObjectExplain.getJSONArray("items");
            if (Objects.equals(CustomerManagementEnum.NAME.getAttr(), attr)
                    || Objects.equals(CustomerManagementEnum.PHONE.getAttr(), attr)
                    || Objects.equals(CustomerManagementEnum.ADDRESS.getAttr(), attr)) {
                continue;
            }
            if (Objects.equals(fieldType, FieldTypeEnum.TEXT.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.TEXTAREA.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.NUM.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    Object object = defaultAttr.getObject("defaultValue", Object.class);
                    addObject.put(attr, object);
                }


            } else if (Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    Long object = defaultAttr.getLong("defaultValue");
                    addObject.put(attr, object);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())) {
                if (Objects.nonNull(itemList)) {
                    for (int n = 0; n < itemList.size(); n++) {
                        JSONObject item = itemList.getJSONObject(n);
                        Boolean checked = item.getBoolean("checked");
                        if (checked != null && checked) {
                            JSONObject object = new JSONObject();
                            object.put("text", item.getString("text"));
                            object.put("value", item.getString("value"));
                            addObject.put(attr, object);
                            continue;
                        }
                    }
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                JSONArray checkboxGroupArray = new JSONArray();
                if (Objects.nonNull(itemList)) {
                    for (int n = 0; n < itemList.size(); n++) {
                        JSONObject item = itemList.getJSONObject(n);
                        Boolean checked = item.getBoolean("checked");
                        if (checked != null && checked) {
                            checkboxGroupArray.add(item);
                        }
                    }
                }
                addObject.put(attr, checkboxGroupArray);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    JSONArray defaultJSONArray = defaultAttr.getJSONArray("defaultValue");
                    addObject.put(attr, defaultJSONArray);
                }
            }
        }
    }
    
    /**
     * @param fineClueGetEnableBuinessDTO
     * @Author chenshan
     * @Description 获取当前开启的应用
     * @Date 2021/11/8 14:09
     **/
    @Override
    public FineClueGetEnableBuinessVO getEnableBuiness(FineClueGetEnableBuinessDTO fineClueGetEnableBuinessDTO) throws XbbException {
        FineClueGetEnableBuinessVO fineClueGetEnableBuinessVO = new FineClueGetEnableBuinessVO();
        Set<String> permSet = fineClueGetEnableBuinessDTO.getLoginUser().getPermSet();
        String corpid = fineClueGetEnableBuinessDTO.getCorpid();
        if ( (permSet.contains(ProPermissionAliasEnum.CRM.getAlias()) || permSet.contains(ProPermissionAliasEnum.CUSTOMER_MANAGEMENT.getAlias()))&&permSet.contains(ProPermissionAliasEnum.CUSTOMER_ADD.getAlias())) {
            fineClueGetEnableBuinessVO.setEnableCustomer(1);
        }
        Boolean standardWithFeeType = packageHelp.isStandardWithFeeType(corpid);
        boolean enableWithApp = marketManagementBusinessHelp.isEnableWithApp(corpid);
        if ((permSet.contains(ProPermissionAliasEnum.MARKET_MANAGEMENT.getAlias()) || permSet.contains(ProPermissionAliasEnum.CLUE.getAlias()))
                && !standardWithFeeType && enableWithApp && permSet.contains(ProPermissionAliasEnum.CLUE_ADD.getAlias())) {
            fineClueGetEnableBuinessVO.setEnableClue(1);
        }
        return fineClueGetEnableBuinessVO;
    }

    @Override
    public FineClueMsgVO getUseDosage(FineClueGetUseDosageDTO fineClueGetUseDosageDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        String phone = fineClueGetUseDosageDTO.getPhone();
        List<String> data = fineClueGetUseDosageDTO.getData();
        Integer operateTime = fineClueGetUseDosageDTO.getOperateTime();
        String serialNumber = fineClueGetUseDosageDTO.getSerialNumber();
        Integer useDosage = fineClueGetUseDosageDTO.getUseDosage();
        LOG.info("useDosage:{},data:{}",useDosage,data);
        //从redis中取出所有的id和companyName
        String key = phone + "____" + serialNumber;

        String value = paasRedisHelper.getValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, key);
        if (Objects.isNull(value)){
            throw  new XbbException(FineClueErrorCodeEnum.API_ERROR_280011);
        }
        JSONObject jsonObject = JSONObject.parseObject(value, JSONObject.class);
        String corpid = jsonObject.getString(StringConstant.CORPID);
        String userId = jsonObject.getString("userId");
        String httpHeader = jsonObject.getString("httpHeader");
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        String userName = jsonObject.getString("userName");
        String tag = jsonObject.getString("tag");
//        int count = 0;
        LOG.info("sanfangPid1:{}",data);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String id = object.getString("id");
            for (String pid : data) {
                LOG.info("sanfangPid2:{},id:{}",pid,id);
                //如果三方发送来的pid和xbb缓存的id相同，说明本条线索需要记录解锁日志
                if (Objects.equals(id,pid)){
                    FineClueConsumptionEntity fineClueConsumptionEntity = fineClueConsumptionModel.getByPid(corpid, pid, ExternalDataSourceEnum.FINE_CLUE.getType());
                    if (Objects.nonNull(fineClueConsumptionEntity)) {
                        fineClueConsumptionEntity.setStatus(FineClueStatusEnum.UNLOCK.getCode());
                        fineClueConsumptionModel.update(fineClueConsumptionEntity);
                    }

                    String companyName = object.getString("companyName");
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_UNLOCKCONTACTINFO), userName);
                    mongoLogHelp.saveLoggerByInsert(corpid, userId, userName, companyName, memo, id, httpHeader, OperateModuleTypeEnum.SOUKE, OperateTypeEnum.UNLOCKCONTACTINFO);
//                    count ++;
                }
            }
        }

        //存储转线索的任务状态 线索消耗量
        TransferClueParamPOJO transferClueParamPOJO = new TransferClueParamPOJO();
        transferClueParamPOJO.setUseDosage(useDosage);
        transferClueParamPOJO.setFinish(true);
        String redisKey = corpid + "___" + tag;
        paasRedisHelper.setValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, redisKey, transferClueParamPOJO, RedisTimeConstant.TEN_MINUTES);

        return fineClueMsgVO;
    }

    @Override
    public FineClueMsgVO getMoreConsumption(BaseDTO baseDTO) throws XbbException {
        FineClueMsgVO fineClueMsgVO = new FineClueMsgVO();
        //推送一条销售机会
        CompanyEntity byKey = companyModel.getByKey(baseDTO.getCorpid());
        AppModuleSaveDTO saveDTO = new AppModuleSaveDTO();
        BeanUtil.copyProperties(baseDTO, saveDTO);
        saveDTO.setCompanyName(byKey.getCorpName());
        saveDTO.setAlias(ValueAddedTypeEnum.SEARCH_CUSTOMER_INC_PACKAGE.getAlias());
        appModuleService.addSalesOpportunity(saveDTO);
        return fineClueMsgVO;
    }

    @Override
    public TransferClueStatusVO getTransferStatus(TransferClueStatusDTO transferClueStatusDTO) throws XbbException {
        TransferClueStatusVO transferClueStatusVO = new TransferClueStatusVO();
        String corpid = transferClueStatusDTO.getCorpid();
        String userId = transferClueStatusDTO.getUserId();
        String tag = transferClueStatusDTO.getTag();

        //存储转线索的任务状态 线索消耗量
        String redisKey2 = corpid + "___" + tag;
        String value2 = paasRedisHelper.getValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, redisKey2);
        if (Objects.isNull(value2)){
            throw  new XbbException(FineClueErrorCodeEnum.API_ERROR_280011);
        }
        TransferClueParamPOJO paramPOJO = JSONObject.parseObject(value2, TransferClueParamPOJO.class);
        Boolean finish = paramPOJO.getFinish();
        if (!finish){
            transferClueStatusVO.setFinish(0);
            return transferClueStatusVO;
        }
        Integer useDosage = paramPOJO.getUseDosage();
        //存储转线索的任务状态 转成功的条数。。。
        String redisKey = corpid + "_" + tag;
        String value = paasRedisHelper.getValue(FineClueUrlConstant.FINE_CLUE_COMPANY_KEY, redisKey);
        if (Objects.isNull(value)){
            throw  new XbbException(FineClueErrorCodeEnum.API_ERROR_280011);
        }
        paramPOJO = JSONObject.parseObject(value, TransferClueParamPOJO.class);
        int successNum = paramPOJO.getSuccessNum();
        int falseNum = paramPOJO.getFalseNum();
        int type = paramPOJO.getType();
        Boolean isPublicSea = paramPOJO.getIsPublicSea();
        int clueCount = paramPOJO.getClueCount();
        String formName = "";
        if (isPublicSea){
            if (Objects.equals(type,1)){
                formName = I18nMessageUtil.getMessage(MessageConstant.CUSTOMER_HIGH_SEAS_POOL);
            } else {
                formName = I18nMessageUtil.getMessage(MessageConstant.CLUE_HIGH_SEAS_POOL);
            }
        } else {
            if (Objects.equals(type,1)){
                formName = I18nMessageUtil.getMessage(MessageConstant.CUSTOMER_FORM);
            } else {
                formName = I18nMessageUtil.getMessage(MessageConstant.CLUE_FORM);
            }
        }

        transferClueStatusVO.setFinish(1);
        transferClueStatusVO.setSuccessNum(successNum);
        transferClueStatusVO.setFaileNum(falseNum);
        transferClueStatusVO.setClueCount(clueCount);
        transferClueStatusVO.setFormName(formName);
        transferClueStatusVO.setUseDosage(useDosage);

        return transferClueStatusVO;
    }
}
